Topic 4- File Handling
Tags: #◇CCPROG2 #◇C Programming #◇Programming #◇Computer Science #◇Files #◇Data Analysis #◇Searching #◇Structured Data #◇Structured Programming #◇Memory Management
◇Overview
File handling in C allows programs to read from and write to files on disk using the
<stdio.h>library and theFILEpointer type.
◇Key Concepts
FILE * pointer represents an open file stream fopen() opens a file; fclose() closes it Modes: "r" (read), "w" (write), "a" (append), "rb"/"wb" (binary) Text I/O: fprintf, fscanf, fgets, fputs Binary I/O: fread, fwrite
◇Details / Theory
Opening and Closing Files
FILE *fp = fopen("data.txt", "r"); // Open for reading
if (fp == NULL) {
printf("Error: Cannot open file.\n");
return 1;
}
// ... use the file ...
fclose(fp); // Always close when done
File Modes
| Mode | Description |
|---|---|
"r" | Read (file must exist) |
"w" | Write (creates/overwrites) |
"a" | Append (creates if needed) |
"r+" | Read + Write (file must exist) |
"w+" | Read + Write (creates/overwrites) |
"rb" | Read binary |
"wb" | Write binary |
Writing to a Text File
FILE *fp = fopen("output.txt", "w");
if (fp != NULL) {
fprintf(fp, "Name: %s\n", "Alice");
fprintf(fp, "Score: %d\n", 95);
fputs("End of record.\n", fp);
fclose(fp);
}
Reading from a Text File
FILE *fp = fopen("data.txt", "r");
char line[256];
// Read line by line
while (fgets(line, sizeof(line), fp) != NULL) {
printf("%s", line);
}
fclose(fp);
// Structured reading with fscanf
FILE *fp = fopen("students.txt", "r");
char name[50];
int age;
float gpa;
while (fscanf(fp, "%s %d %f", name, &age, &gpa) == 3) {
printf("%s is %d with GPA %.2f\n", name, age, gpa);
}
fclose(fp);
Binary File I/O
typedef struct {
char name[50];
int age;
} Student;
// Write binary
FILE *fp = fopen("students.bin", "wb");
Student s = {"Alice", 20};
fwrite(&s, sizeof(Student), 1, fp);
fclose(fp);
// Read binary
fp = fopen("students.bin", "rb");
Student s2;
fread(&s2, sizeof(Student), 1, fp);
printf("%s, %d\n", s2.name, s2.age);
fclose(fp);
File Position Functions
| Function | Description |
|---|---|
ftell(fp) | Current position in bytes |
fseek(fp, offset, origin) | Move to position |
rewind(fp) | Go back to beginning |
Origins for fseek: SEEK_SET (beginning), SEEK_CUR (current), SEEK_END (end).
Checking for End of File
while (!feof(fp)) {
// Read data...
}
Note: Prefer checking the return value of
fread/fgets/fscanfrather than usingfeof()in loop conditions.
◇Common Pitfalls
Not checking if fopen() returns NULL — leads to segfault. Forgetting to fclose() — causes resource leaks and data loss. Using "w" mode when intending to append — overwrites the file. Using feof() as a loop condition — can read one extra iteration. Mixing text and binary modes on Windows (newline translation issues).
◇Summary
TL;DR — File handling uses
FILE *withfopen/fclose. Usefprintf/fscanf/fgetsfor text andfread/fwritefor binary. Always check forNULLon open and close files when done.
◇Links
Related: ◇Strings — ◇Structs — ◇Recursion — ◇What is an Array Source / Reference:
◇References & Navigation
- Previous Topic: ◇Structs
- Next Topic: ◇Recursion
- Related Notes: ◇Files I-O (via Streams), ◇Computer Hardware - IO Devices
ACTIVE RECALL VERIFICATION
Select an answer to verify conceptual comprehension and reveal the technical rationale.
Which library is required for file handling in C?
What type of pointer is used to represent an open file stream in C?
What is the result of using the "w" mode with fopen() on an existing file?
Which function must always be called when you are finished using an open file?
What does fopen() return if it fails to open a file?
Which function is specifically used for structured reading of text files, similar to reading from standard input?
Which functions are primarily used for reading and writing binary files in C?
What does the ftell(fp) function return?
Why is using feof() directly as a loop condition generally discouraged?
What origin constant is used with fseek() to move relative to the beginning of the file?